﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.OleDb;
using System.Data;
using System.Globalization;
using System.IO;

namespace Timesheet
{
    class JIRASystem : IJIRASystem
    {
        public JIRASystem(string account)
        {
            this._username = account;
        }

        public String Username
        {
            get { return _username; }
            set { _username = value; }
        }

        private String _username;

        #region IJIRASystem 成员

        //get all the work logs for a week
        public List<WorkLog> GetWorkLogs(DateTime weekend)
        {
            String start_time = weekend.Year.ToString("D4") +  weekend.Month.ToString("D2") +  (weekend.Day).ToString("D2");
            List<WorkLog> worklogs = new List<WorkLog>();
            DataSet worklogDataSet = getWorklogDataSet(start_time);
            if (worklogDataSet.Tables[0] != null) {
                DataTable worklogTable = worklogDataSet.Tables[0];
                String jiraNumber;
                String author;
                Double effort;
                String comment;
                String project;
                String issueType;
                DateTime date;
                String parentJira;
                String parentType;
                WorkLog worklog;
                String taskCategory;
                foreach (DataRow dr in worklogTable.Rows) {
                    jiraNumber = dr["Pkey"].ToString();
                    author = dr["author"].ToString();
                    effort = Double.Parse(dr["effort"].ToString());
                    comment = dr["worklogbody"].ToString();
                    date = DateTime.Parse(dr["startdate"].ToString());
                    parentType = dr["parentType"].ToString();
                    taskCategory = dr["task_category"].ToString();
                    //TODO: make it able to configure these
                    project = "";
                    issueType = "";
                    parentJira = "";
                    worklog = new WorkLog(jiraNumber, author, effort, comment, project, issueType, date, parentJira, parentType, taskCategory);
                    worklogs.Add(worklog);
                }
            }
            return worklogs;
        }

        // generate dictionary for OpenAirTimeSheet via worklogs from DB
        public Dictionary<IOpenAirTimeSheetItem, List<WorkLog>> GenerateOpenAirTimeSheet(List<WorkLog> workLogs, string[] configurations)
        {
            Dictionary<IOpenAirTimeSheetItem, List<WorkLog>> dic = new Dictionary<IOpenAirTimeSheetItem,List<WorkLog>>();
            foreach (WorkLog worklog in workLogs) { 
                //create match string for worklog
                string matchString = "TaskCateGory["+ worklog.TaskCategory +"]Project[" + worklog.Project + "]|JiraNumber[" + worklog.JiraNumber + "]|Comment[" + worklog.Comment + "]|IssueType[" + worklog.IssueType + "]|ParentJira[" + worklog.ParentJira + "]|ParentType[" + worklog.ParentType + "]";
                foreach (string configString in configurations) {
                    //splite the congig string which comes form config.dat
                    string[] spliteConfigString = configString.Split('|');
                    //If it's matched, then add worklog to dictionary
                    if (!String.IsNullOrEmpty(spliteConfigString[0]) &&
                        matchString.Contains(spliteConfigString[0])) { 
                        if(String.IsNullOrEmpty(spliteConfigString[1]) || String.IsNullOrEmpty(spliteConfigString[2]) ){
                            continue;
                        }
                        OpenAirTimesheetItem tempOpenAirTimeSheetItem = new OpenAirTimesheetItem(spliteConfigString[1], spliteConfigString[2],this.getDateString(worklog.Date));
                        List<WorkLog> workLogsForItem = new List<WorkLog>();
                        if (dic.TryGetValue(tempOpenAirTimeSheetItem, out workLogsForItem))
                        {
                            workLogsForItem.Add(worklog);
                        }
                        else {
                            workLogsForItem = new List<WorkLog>();
                            workLogsForItem.Add(worklog);
                            dic.Add(tempOpenAirTimeSheetItem, workLogsForItem);
                        }
                        break;
                    }
                }
            }
            return dic;
        }

        #endregion

        //TODO: Move this to configuration file
        private const string ConnectString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=jirareader;Password=jl4racc;Initial Catalog=jira_reporting;Data Source=10.1.11.3";
        private DataSet getWorklogDataSet(String start_time)
        {
            if (String.IsNullOrEmpty(_username)) {
                throw new Exception("jira system's user name is null or empty, unable to get the worklog");
            }
            String sqlStatment = File.ReadAllText("worklog_sql.dat");
            
            sqlStatment = sqlStatment.Replace("@resource", "'" + Username + "'");
            sqlStatment = sqlStatment.Replace("@week_ending_dte","'" + start_time + "'");

            
            OleDbConnection connection = new OleDbConnection(ConnectString);
            DataSet ds = new DataSet();
            try
            {
                connection.Open();
                Console.Out.Write(sqlStatment);
                OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sqlStatment, connection); 
                oledbAdapter.Fill(ds);
                oledbAdapter.Dispose();
            }
            finally {
                connection.Close();
            }

            return ds;
        }

        private string getDateString(DateTime date)
        {
            return date.Year.ToString("D4") + date.Month.ToString("D2") + date.Day.ToString("D2");
        }

    }
}
